import { logout } from '@/api/modules/user';
import {
  SET_MENUS, SET_USER_NAME, LOGIN_OUT, SET_AUTH_KEYS,
} from '../actionTypes';

// state
const storeState = {
  userName: '',
  menus: [],
  authKeys: [],
};

const actions = {
  [SET_MENUS]({ commit }) {
    return new Promise((resolve) => {
      // TODO: 调用后端接口获取用户基本信息和权限信息

      const userInfo = {
        authorization: 'TGT-820659-ik8G-Cexfz5NnqAicN-uYh5NuPmjNKRGlu6R6l6B0hha5jV9u9E39wH5X7vrogVuB8M-longhu',
        loginName: 'dony',
        loginTime: 1746978336887,
        userId: '39e9a23d-2a85-4f36-a4ac-cd6118566fa7',
        userName: 'dony',
        realName: '明豪',
      };

      const functions = [
        {
          code: 'FM_COCKPIT',
          id: '46fd4232-e210-480c-b3f4-863f79206345',
          name: '首页',
        }
      ];

      // 获取所有的authKeys，包括组件下面配置的操作
      const authKeys = functions.map((func) => func.code);

      commit(SET_AUTH_KEYS, authKeys);
      commit(SET_MENUS, functions);
      commit(SET_USER_NAME, userInfo.realName);
      localStorage.setItem('_user_id', userInfo.userId);
      resolve({ menus: functions });
    });
  },
  [LOGIN_OUT]({ commit }) {
    return new Promise((resolve, reject) => {
      logout().then(({ data }) => {
        commit(SET_MENUS, []);
        commit(SET_AUTH_KEYS, []);
        commit(SET_MENUS, '');
        resolve(data);
      }).catch((error) => {
        reject(new Error(error));
      });
    });
  },
};

// mutations
const mutations = {
  [SET_MENUS](state, menus) {
    state.menus = menus;
  },
  [SET_AUTH_KEYS](state, keys) {
    state.authKeys = keys;
  },
  [SET_USER_NAME](state, userName) {
    state.userName = userName;
  },
};

export default {
  namespaced: true,
  state: storeState,
  actions,
  mutations,
};
